<template>
    <el-form ref="plantFormRef" :model="plantForm" label-width="100px">
        <div class="add-plant-title">上传作品</div>
        <el-form-item label="作品名" required>
            <el-input v-model="plantForm.plantName" placeholder="请输入作品名"></el-input>
        </el-form-item>
        <el-form-item label="植物学名">
            <el-input v-model="plantForm.plantSpecific" placeholder="请输入植物学名"></el-input>
        </el-form-item>
        <el-form-item label="拉丁学名">
            <el-input v-model="plantForm.latinName" placeholder="请输入植物拉丁学名"></el-input>
        </el-form-item>
        <el-form-item required label="植物图片：">
            <el-upload class="picture-uploader" :action="''" :auto-upload="false" :show-file-list="false"
                :on-change="handlePictureChangeIcon">
                <img v-if="imageUrl" :src="imageUrl" class="picture">
                <el-icon v-else class="picture-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="种群" required>
            <el-select @change="categoryChange" v-model="plantForm.categoryId" class="m-2" placeholder="请选择种群">
                <el-option v-for="item in categoryOptions" :label="item.categoryName" :value="item.categoryId" />
            </el-select>
        </el-form-item>
        <el-form-item label="科属">
            <el-cascader v-model="familyIdArray.familyId" :options="familyList" :props="props1" placeholder="请选择科属"
                clearable />
        </el-form-item>
        <el-form-item label="植物描述">
            <el-input v-model="plantForm.plantDescription" placeholder="请输入植物描述" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="拍摄地址" required>
            <v-distpicker :province="select.province" :city="select.city" :area="select.area" class="address-picker"
                @province="selectProvince" @city="selectCity" @area="selectArea"></v-distpicker>
        </el-form-item>
        <el-form-item label="详细图片：">
            <el-upload class="picture-uploader" list-type="picture-card" :http-request="pictureListUpload" :action="''"
                :auto-upload="true" :file-list="pictureList" :on-remove="handleRemove" multiple name="img">
                <el-icon class="picture-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item class="add-plant-button">
            <el-button type="primary" @click="addPlant()">确认上传</el-button>
        </el-form-item>
    </el-form>
    <!-- <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog> -->
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import VDistpicker from 'v-distpicker'
import { useCategoryListApi, useFamilyTreeApi } from '@/api/plant/category'
import { useUploadPictureApi } from '@/api/user/user';
import { useSavePlantApi } from '@/api/plant/plant'
import { useRequest } from 'vue-request';
import { ElMessage, type UploadProps, ElMessageBox } from 'element-plus'
import store from '@/stores';
import { photoCompress, convertBase64UrlToFile } from '@/util/imageCompress'



const router = useRouter()
const route = useRoute()
const plantForm = reactive({
    plantName: '',
    plantSpecific: '',
    latinName: '',
    categoryId: '',
    familyId: '',
    genusId: '',
    plantDescription: '',
    address: '',
    plantPicture: '',
    pictures: '',
    userId: '',
})
const imageUrl = ref()
const pictureList = ref()
const select = reactive({
    province: '',
    city: '',
    area: ''
})
const pageParam = reactive({
    currentPage: 1,
    pageSize: 1000
})
const familyList = reactive([])
const familyIdArray = reactive({
    familyId: '',
})
const props1 = {
    expandTrigger: 'hover' as const,
    checkStrictly: true,
    value: 'familyId',
    label: 'familyName',
    children: 'child'
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)


const { data } = useRequest(useCategoryListApi(pageParam))
const categoryOptions = computed(() => {
    return data.value?.data || []
})
const categoryChange = async (val: any) => {
    familyList.length = 0
    const { data } = await useFamilyTreeApi(val)
    Object.assign(familyList, data)
}

const selectProvince = (data: any) => {
    select.province = data.value
}
const selectArea = (data: any) => {
    select.area = data.value
}
const selectCity = (data: any) => {
    select.city = data.value
}


const handlePictureChangeIcon: UploadProps['onChange'] = (file, fileList) => {
    const isJPG = file.raw!.type === 'image/jpeg'
    const isPNG = file.raw!.type === 'image/png'
    const isLt10M = file.raw!.size / 1024 / 1024 < 10 //限制上传文件的大小
    if (!isPNG && !isJPG) {
        ElMessage({
            message: '上传图片只能是 JPG/PNG 格式!',
            type: 'warning'
        })
        return false
    } else {
        if (!isLt10M) {
            ElMessage({
                message: '图片内存太大!',
                type: 'error'
            })
            return false
        }
        imageUrl.value = URL.createObjectURL(file.raw!);//赋值图片的url，用于图片回显功能
        if (file.raw!.size > 1048576) {
            photoCompress(file.raw!,
                {
                    quality: 0.1,
                    // width: 0,
                    // height: 0
                },
                (base64Codes: any) => {
                    let newFile = convertBase64UrlToFile(base64Codes, file.name)
                    // console.log(newFile)
                    uploadImg(newFile)
                }
            )
        } else {
            uploadImg(file.raw)//调用上传图片api接口
        }
    }
}
const uploadImg = async (file: any) => {
    let formData = new FormData()
    formData.append('img', file)
    await useUploadPictureApi(formData)
        .then((res) => {
            const { data } = res
            plantForm.plantPicture = data
        })
}

const uploadImgs = async (formData: any) => {
    await useUploadPictureApi(formData)
        .then((res) => {
            const { data } = res
            if (plantForm.pictures) {
                plantForm.pictures = plantForm.pictures + '+' + data
            } else {
                plantForm.pictures = data
            }
        })
}

const pictureListUpload = async (file: any) => {
    let formData = new FormData()
    if (file.file.size > 1048576) {
        photoCompress(file.file,
            {
                quality: 0.1,
                // width: 0,
                // height: 0
            },
            (base64Codes: any) => {
                const newFile = convertBase64UrlToFile(base64Codes, file.file.name)
                // console.log(newFile)
                formData.append('img', newFile)
                uploadImgs(formData)
            }
        )
    } else {
        formData.append('img', file.file)
        uploadImgs(formData)
    }
    // console.log(formData)

}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    // console.log(uploadFile, uploadFiles)
}

const addPlant = async () => {
    plantForm.userId = store.useUserStore.user.userId
    plantForm.address = select.province + '/' + select.city + '/' + select.area
    plantForm.familyId = familyIdArray.familyId[0]
    if (familyIdArray.familyId[1]) {
        plantForm.genusId = familyIdArray.familyId[1]
    }
    await useSavePlantApi(plantForm)
        .then((res) => {
            ElMessage({
                message: '上传成功',
                type: 'success'
            })
            refresh()
        })
}


function refresh() {
    // 刷新当前路由
    const { fullPath } = route
    router.replace({
        path: '/redirect' + fullPath
    })
}


</script>

<style lang="scss" scoped>
.add-plant-title {
    display: flex;
    justify-content: center;
    margin-bottom: 35px;
    font-size: 24px;
    color: #444;
    letter-spacing: 4px;
}

.add-plant-button {
    :deep(.el-button--primary) {
        margin-top: 10px;
        width: 100%;
        height: 45px;
        font-size: 18px;
        letter-spacing: 8px;
    }
}

.picture-uploader .picture {
    width: 178px;
    height: 178px;
    display: block;
}

.picture-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.picture-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.picture-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>